<template>
  <div class="edit-purchase-request">
    <el-card class="box-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>编辑采购申请</h3>
        </div>
      </template>
      
      <el-form
        v-if="!loading && purchaseRequest && purchaseRequest.id"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="purchase-form"
      >
        <el-form-item label="物品名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入物品名称" />
        </el-form-item>
        
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :precision="0" :step="1" />
        </el-form-item>
        
        <el-form-item label="预算" prop="budget">
          <el-input-number 
            v-model="form.budget"
            :precision="2" 
            :step="100" 
            :controls="false"
          >
            <template #prepend>¥</template>
          </el-input-number>
        </el-form-item>
<!--        <el-form-item label="预算" prop="budget">-->
<!--          <el-input-number -->
<!--            v-model="form.budget" -->
<!--            :min="0" -->
<!--            :precision="2" -->
<!--            :step="100" -->
<!--            :controls="false"-->
<!--          >-->
<!--            <template #prepend>¥</template>-->
<!--          </el-input-number>-->
<!--        </el-form-item>-->
        
        <el-form-item label="申请理由" prop="reason">
          <el-input 
            v-model="form.reason" 
            type="textarea" 
            rows="4" 
            placeholder="请输入申请理由" 
          />
        </el-form-item>
        
        <el-form-item label="当前附件">
          <div v-if="purchaseRequest.attachmentPath" class="current-attachment">
            <span>已上传附件</span>
            <el-button 
              link 
              type="primary" 
              @click="downloadAttachment"
            >
              查看附件
            </el-button>
          </div>
          <div v-else>无附件</div>
        </el-form-item>
        
        <el-form-item label="更新附件">
          <el-upload
            class="upload-demo"
            :action="null"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            :file-list="fileList"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传PDF格式文件，如采购报价单等。上传新文件将替换原有附件。
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存修改</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
      
      <div v-else-if="!loading && (!purchaseRequest || !purchaseRequest.id)" class="empty-data">
        <el-empty description="未找到采购申请数据" />
        <el-button class="mt-3" type="primary" @click="$router.push('/purchase-requests')">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getPurchaseRequestById, updatePurchaseRequest } from '@/api/purchase-request'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const fileList = ref([])
const selectedFile = ref(null)
const purchaseRequest = ref({})

// 表单数据
const form = reactive({
  itemName: '',
  quantity: 1,
  budget: 0,
  reason: ''
})

// 表单验证规则
const rules = {
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value < 1) {
          callback(new Error('数量必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur' }
    // { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  budget: [
    { required: true, message: '请输入预算', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('预算不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'  }
    // { type: 'number', min: 0, message: '预算不能为负数', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入申请理由', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取采购申请详情
const fetchPurchaseRequest = async () => {
  const id = route.params.id
  if (!id) return
  
  loading.value = true
  try {
    const response = await getPurchaseRequestById(id)
    // 检查响应格式，确保数据正确赋值
    purchaseRequest.value = response.data || response
    
    // 检查是否有数据
    if (!purchaseRequest.value || !purchaseRequest.value.id) {
      ElMessage.error('未找到采购申请数据')
      return
    }
    
    // 检查是否可以编辑（只能编辑待审批的申请）
    if (purchaseRequest.value.status !== 'PENDING') {
      ElMessage.error('只能编辑待审批的申请')
      router.push(`/purchase-requests/${id}`)
      return
    }
    
    // 填充表单数据
    form.itemName = purchaseRequest.value.itemName
    form.quantity = purchaseRequest.value.quantity
    form.budget = purchaseRequest.value.budget
    form.reason = purchaseRequest.value.reason
  } catch (error) {
    console.error('获取采购申请详情失败:', error)
    ElMessage.error('获取采购申请详情失败')
  } finally {
    loading.value = false
  }
}

// 处理文件变更
const handleFileChange = (file) => {
  // 验证文件类型
  const isPDF = file.raw.type === 'application/pdf'
  if (!isPDF) {
    ElMessage.error('只能上传PDF文件!')
    fileList.value = []
    return false
  }
  
  // 验证文件大小（小于10MB）
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    fileList.value = []
    return false
  }
  
  selectedFile.value = file.raw
  return true
}

// 处理超出文件数量限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 处理移除文件
const handleRemove = () => {
  selectedFile.value = null
}

// 下载附件
const downloadAttachment = () => {
  if (purchaseRequest.value && purchaseRequest.value.attachmentPath) {
    window.open(`/api/purchase-requests/${purchaseRequest.value.id}/attachment`, '_blank')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const formData = new FormData()
        formData.append('purchaseRequest', new Blob([JSON.stringify(form)], { type: 'application/json' }))
        
        if (selectedFile.value) {
          formData.append('attachment', selectedFile.value)
        }
        
        const result = await updatePurchaseRequest(purchaseRequest.value.id, formData)
        console.log('更新结果:', result)
        ElMessage.success('采购申请更新成功')
        router.push(`/purchase-requests/${purchaseRequest.value.id}`)
      } catch (error) {
        console.error('更新采购申请失败:', error)
        ElMessage.error('更新采购申请失败')
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
      return false
    }
  })
}

onMounted(() => {
  fetchPurchaseRequest()
})
</script>

<style scoped>
.edit-purchase-request {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.purchase-form {
  max-width: 800px;
}

.current-attachment {
  display: flex;
  align-items: center;
  gap: 10px;
}

.empty-data {
  padding: 40px 0;
  display: flex;
  justify-content: center;
}
</style> 